package com.aefottt.struggle_star.fragment;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aefottt.struggle_star.DataListenerManager;
import com.aefottt.struggle_star.R;
import com.aefottt.struggle_star.activity.DataActivity;
import com.aefottt.struggle_star.activity.MainWrapperActivity;
import com.aefottt.struggle_star.activity.StarActivity;
import com.aefottt.struggle_star.adapter.MainRecyclerAdapter;
import com.aefottt.struggle_star.bean.DataBean;
import com.aefottt.struggle_star.bean.ListBean;
import com.aefottt.struggle_star.bean.TaskBean;
import com.aefottt.struggle_star.util.DateUtil;
import com.aefottt.struggle_star.util.PrefUtil;
import com.aefottt.struggle_star.view.NotifyToast;
import com.google.android.material.bottomappbar.BottomAppBar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.shape.MaterialShapeDrawable;
import com.google.android.material.shape.ShapeAppearanceModel;
import com.google.android.material.shape.TriangleEdgeTreatment;

import org.litepal.LitePal;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class MainFragment extends Fragment {
    private final static String FILE_USER_INFO = "user_info";
    private final static String KEY_IS_FIRST_ENTER = "isFirstEnter";
    private final static String KEY_LAST_ENTER_TIME = "lastEnterTime";
    private final static String KEY_IS_FIRST_CREATE = "isFirstCreate";

    private ImageView ivExploreStars, ivConcentrate;
    private BottomAppBar bottomAppBar;
    private FloatingActionButton fabAdd;
    private TextView tvListName, tvListDesc;

    private RecyclerView rv;
    private LinearLayoutManager manager;
    private MainRecyclerAdapter adapter;
    private final List<ListBean> listBeanList = new ArrayList<>();
    private ListBean currentList;
    private final List<DataBean> dataBeans = new ArrayList<>();

    private MainWrapperActivity.VpChangeListener vpChangeListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        initView(view);
        initListener();
        initData();
        initEvent();
        return view;
    }

    private void initListener() {
        // 跳转专注界面
        ivConcentrate.setOnClickListener(v -> {
            if (vpChangeListener != null) {
                vpChangeListener.changeVp(0);
            }
        });
        // 跳转探索星球界面
        ivExploreStars.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), StarActivity.class);
            int[] viewLocation = new int[2];
            v.getLocationInWindow(viewLocation);
            intent.putExtra("posX", viewLocation[0] + v.getWidth() / 2);
            intent.putExtra("posY", viewLocation[1] + v.getHeight() / 2);
            startActivity(intent);
            // 取消系统默认的跳转动画
            Objects.requireNonNull(getActivity()).overridePendingTransition(0, 0);
        });
        // 跳转添加待办界面
        fabAdd.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), DataActivity.class);
            intent.putExtra("listId", 1); // 添加时默认所属清单为“今日待办”
            if ((boolean) (PrefUtil.getInstance(getActivity()).get(FILE_USER_INFO, KEY_IS_FIRST_CREATE, true))){
                intent.putExtra("isFirst", true);
            }
            startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
        });
    }

    private void initEvent() {
        DataListenerManager.getInstance(getActivity()).setListener(new MyDataListenerManager(this));
    }

    /**
     * 使用静态内部类，持有外部Activity的弱引用，防止内存泄漏
     */
    static class MyDataListenerManager implements DataActivity.OnDataActivityListener{
        private final WeakReference<MainFragment> fragment;
        private boolean isDelete;

        public MyDataListenerManager(MainFragment fragment) {
            this.fragment = new WeakReference<>(fragment);
        }

        @Override
        public void onCreate(TaskBean taskBean) {
            fragment.get().dataBeans.add(taskBean.getRank(), taskBean);
            fragment.get().adapter.notifyItemInserted(taskBean.getRank());
            new NotifyToast.Builder(fragment.get().getActivity())
                    .setContent("成功创建待办<"+taskBean.getDataTitle()+">")
                    .setBtnText("撤销")
                    .setBtnClickListener(toast -> {
                        fragment.get().dataBeans.remove(taskBean);
                        fragment.get().adapter.notifyItemRemoved(taskBean.getRank());
                        taskBean.delete();
                        taskBean.deleteSubTasks();
                    }).showToast(Gravity.TOP);
        }

        @Override
        public void onDelete(TaskBean taskBean) {
            isDelete = true;
            fragment.get().dataBeans.remove(taskBean);
            Log.e("Main","rank:"+taskBean.getRank());
            fragment.get().adapter.notifyItemRemoved(taskBean.getRank());
            new NotifyToast.Builder(fragment.get().getActivity())
                    .setContent("成功删除待办<"+taskBean.getDataTitle()+">")
                    .setBtnText("撤销")
                    .setBtnClickListener(toast -> {
                        isDelete = false;
                        fragment.get().dataBeans.add(taskBean.getRank(), taskBean);
                        fragment.get().adapter.notifyItemInserted(taskBean.getRank());
                    }).showToast(Gravity.TOP);
            if (isDelete){
                taskBean.delete();
                taskBean.deleteSubTasks();
            }
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        firstEnter();
        updateTodayList();

        listBeanList.addAll(LitePal.order("rank asc").find(ListBean.class));
        currentList = listBeanList.get(0);
        dataBeans.clear();
        dataBeans.addAll(currentList.getDataBeans());

        tvListName.setText(currentList.getListName());
        tvListDesc.setText(currentList.getListDesc());

        manager = new LinearLayoutManager(getActivity());
        adapter = new MainRecyclerAdapter(getActivity(), dataBeans);
        rv.setLayoutManager(manager);
        rv.setAdapter(adapter);
    }

    /**
     * 第一次登录处理
     */
    private void firstEnter(){
        // 是否第一次登录
        boolean isFirstEnter = (boolean) PrefUtil.getInstance(getActivity()).
                get(FILE_USER_INFO, KEY_IS_FIRST_ENTER, true);
        if (isFirstEnter){
            // 第一次登录时自动创建“今日待办”清单
            ListBean todayList = new ListBean(1, "今日待办",
                    DateUtil.getFormattedTime(System.currentTimeMillis()), 0, 0);
            todayList.save();
            // 记录登录时间
            PrefUtil.getInstance(getActivity()).put(FILE_USER_INFO, KEY_LAST_ENTER_TIME,
                    System.currentTimeMillis());
            PrefUtil.getInstance(getActivity()).put(FILE_USER_INFO, KEY_IS_FIRST_CREATE,
                    true);
        }
        // 如果是今日第一次登录
    }

    /**
     * 更新今日待办清单内容
     */
    private void updateTodayList(){
        ListBean todayList = LitePal.findFirst(ListBean.class);
        if (todayList != null){
            todayList.setListDesc(DateUtil.getFormattedTime(System.currentTimeMillis()));
        }
    }

    private void initView(View view) {
        ivExploreStars = view.findViewById(R.id.iv_main_explore_stars);
        ivConcentrate = view.findViewById(R.id.iv_main_concentrate);
        bottomAppBar = view.findViewById(R.id.bab_main);
        fabAdd = view.findViewById(R.id.fab_main_add);
        tvListName = view.findViewById(R.id.tv_main_toolbar_current_list_name);
        tvListDesc = view.findViewById(R.id.tv_main_toolbar_current_list_desc);
        rv = view.findViewById(R.id.rv_main);
        setBottomAppBar();
    }

    /**
     * 设置BottomAppBar中间为菱形
     */
    private void setBottomAppBar() {
        float triangleSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                36, getResources().getDisplayMetrics());
        float elevationSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                12, getResources().getDisplayMetrics());
        TriangleEdgeTreatment triangleEdgeTreatment = new TriangleEdgeTreatment(triangleSize, true);
        ShapeAppearanceModel shapePathModel = ShapeAppearanceModel.builder()
                .setTopEdge(triangleEdgeTreatment)
                .build();
        MaterialShapeDrawable materialShapeDrawable = new MaterialShapeDrawable(shapePathModel);
        materialShapeDrawable.setTint(Color.WHITE);
        materialShapeDrawable.setPaintStyle(Paint.Style.FILL);
        materialShapeDrawable.setShadowCompatibilityMode(MaterialShapeDrawable.SHADOW_COMPAT_MODE_ALWAYS);
        materialShapeDrawable.initializeElevationOverlay(getActivity());
        materialShapeDrawable.setElevation(elevationSize);
        materialShapeDrawable.setShadowColor(Color.GRAY);
        bottomAppBar.setBackground(materialShapeDrawable);
    }

    public void setVpChangeListener(MainWrapperActivity.VpChangeListener vpChangeListener) {
        this.vpChangeListener = vpChangeListener;
    }
}